# !/usr/bin/env python
# -*- coding: utf-8 -*-
from django.core.exceptions import ObjectDoesNotExist
from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.generics import ListAPIView, CreateAPIView, RetrieveAPIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.viewsets import GenericViewSet
from .models import SpeakerStatus
from .serializers import SpeakerStatusSerializer, SpeakerParamsSerializer
from testcase.models import SpeakerProduct, SpeakerParams
from django.core import serializers
from django_redis import get_redis_connection
from celery_tasks.speaker_monitor.tasks import get_connect_speaker
from .speaker_monitor import get_devices_list

# Create your views here.
from .speaker_monitor import get_speaker_infos
import logging
logger = logging.getLogger('django')


class SpeakerStateAPIView(APIView):
    """
    获取在线设备接口，同时刷新数据库数据
    """
    # 权限检查
    # permission_classes = [IsAuthenticated]

    def get(self, request):
        # get_connect_speaker()

        device_list = get_devices_list()

        # 先将数据库中所有的数据重置
        SpeakerStatus.objects.all().update(connect_status=0)
        logger.info('查询设备列表为：%s' % device_list)
        if len(device_list) == 0:
            return Response({'message': '未找到任何设备，请检查！'}, status=status.HTTP_404_NOT_FOUND)
        else:
            # 遍历数据,如果存在该SN的设备,则更新数据; 如果不存在,则插入一条数据
            for i in device_list:
                device_type = i.get('device_type')
                port = i.get('port')
                obj = SpeakerStatus.objects.filter(port=port)
                # 数据库中查不到数据,新增一条数据
                if len(obj) == 0:
                    SpeakerStatus.objects.create(connect_status=1, port=port, device_type=device_type)
                # 数据库中存在这个数据,则更新数据
                else:
                    obj.update(connect_status=1, port=port, device_type=device_type)

        objs = SpeakerStatus.objects.filter(connect_status=1).order_by('id')
        data = []
        for item in objs:
            tmp = {'id': item.id,
                   'connect_status': item.connect_status,
                   'run_status': item.run_status,
                   'port': item.port,
                   'device_type': item.device_type
                   }
            data.append(tmp)
        return Response(data, status=status.HTTP_200_OK)

        # redis_conn = get_redis_connection('speaker')
        # keys = redis_conn.keys()
        # devices = []
        # for i in keys:
        #     port = i.decode()
        #     device_type = redis_conn.hget(port, 'device_type')
        #     run_status = redis_conn.hget(port, 'run_status')
        #     tmp = {
        #         'port': port,
        #         'device_type': device_type,
        #         'run_status': run_status
        #     }
        #     devices.append(tmp)


class AvailableSpeakerStatusViewSet(ListAPIView):
    """
    查询所有在线设备的状态
    """
    queryset = SpeakerStatus.objects.filter(connect_status=1).order_by("id")
    serializer_class = SpeakerStatusSerializer

    def get_queryset(self):
        type_id = self.request.query_params.get('type_id')
        system_version = SpeakerProduct.objects.get(id=type_id).system_version
        return SpeakerStatus.objects.filter(device_type=system_version, connect_status=1).order_by('id')


class QuerySpeakerParamAPIView(RetrieveAPIView):
    queryset = SpeakerParams.objects.all()
    serializer_class = SpeakerParamsSerializer

    def get_object(self):
        type_id = self.kwargs.get('pk')
        return SpeakerParams.objects.get(speaker_id=type_id)


class SpeakerStatusSetAPIView(APIView):
    def post(self, request):
        port = request.data.get('com')
        run_status = request.data.get('run_status')
        try:
            obj = SpeakerStatus.objects.get(port=port)
            obj.run_status = run_status
            obj.save()
        except ObjectDoesNotExist as e:
            return Response({'message': '未找到相关设备，请检查！'}, status=status.HTTP_404_NOT_FOUND)

        return Response({'message': 'success'}, status=status.HTTP_200_OK)
